package services

import (
	"bufio"
	"github.com/goravel/framework/database/orm"
	"github.com/goravel/framework/facades"
	"github.com/goravel/framework/support/path"
	"github.com/spf13/cast"
	"goravel/app/models"
	"os"
	"strings"
	"time"
)

type AdminLogService struct {
	ParseFile *os.File
	AdminRule *AdminRule
	Path      string
	CommonService
}

func (p *AdminLogService) NewAdminLogService(foldPath string, fileList []string) *AdminLogService {
	return &AdminLogService{
		ParseFile: p.MergeFile(foldPath, fileList),
	}
}

// 读取已经合并的文件
func (p *AdminLogService) LoadMergeFile() *os.File {
	file, err := os.Open(path.Public("storage/sftp/merge/admins_merge.log"))
	if err != nil {
		panic(err)
	}
	return file
}
func (p *AdminLogService) MergeFile(foldPath string, pathList []string) *os.File {
	err := os.MkdirAll(path.Public(foldPath+"merge"), os.ModePerm)

	if err != nil {
		panic(err)
	}
	//看一下里面是否有文件，有就删除，删除之后再创建新文件
	_, err = os.Stat(path.Public(foldPath + "merge/admins_merge.log"))
	if err == nil {
		err = os.Remove(path.Public(foldPath + "merge/admins_merge.log"))
		if err != nil {
			panic(err)
		}
	}
	file, err := os.Create(path.Public(foldPath + "merge/admins_merge.log"))

	writer := bufio.NewWriter(file)
	for i, s := range pathList {
		file_item, _ := os.Open(path.Public(foldPath + s))
		defer file.Close()
		scanner := bufio.NewScanner(file_item)
		for scanner.Scan() {
			writer.WriteString(scanner.Text() + "\n")
		}
		if i == len(pathList)-1 {
			writer.Flush()
		}
	}
	retfile, err := os.Open(path.Public(foldPath + "/merge/admins_merge.log"))
	if err != nil {
		panic(err)
	}
	return retfile
}

// 逐行读取
func (p *AdminLogService) ReadAdminLine(id uint, rids []uint) {
	fileScanner := bufio.NewScanner(p.ParseFile)
	fileScanner.Split(bufio.ScanLines)
	//	每隔10s输出一次日志，fileScanner.Scan()执行完毕后，退出,定义单通道channel
	var flagChan = make(chan bool)
	//定义定时器
	ticker := time.NewTicker(time.Second * 10)
	var user_id uint
	facades.Orm().Query().Model(&models.Configuration{}).Where("id=?", id).Pluck("user_id", &user_id)
	//开启协程
	go func() {
		for {
			select {
			case <-ticker.C:
				p.CommonService.Notice(user_id, `管理员日志解析中|(5:10)`)
			case <-flagChan:
				//fmt.Println("退出")
				ticker.Stop()
				return
			}
		}
	}()
	for fileScanner.Scan() {
		//或者包含了某些字符 Game version
		if fileScanner.Text() == "" || strings.Contains(fileScanner.Text(), "Game version") {
			continue
		}
		txt := fileScanner.Text()
		adminLog := models.AdminLog{}
		adminLog.ConfigurationID = cast.ToInt(id)
		p.AdminRule.HandleFields(txt, &adminLog)

		err := facades.Orm().Query().
			Where("original_text", adminLog.OriginalText).
			FirstOrFail(&adminLog)
		if err == orm.ErrRecordNotFound {
			facades.Orm().Query().Create(&adminLog)
		}
	}
	//fileScanner是否扫描完毕
	if !fileScanner.Scan() {
		flagChan <- true
		p.CommonService.Notice(user_id, `管理员日志解析完成|(5:10)`)
	}
	facades.Orm().Query().Model(&models.DownloadRecord{}).Where("id in (?)", rids).Update("is_need_download_and_parse", 0)
	p.ParseFile.Close()
}
